import { useState } from "react"

const DRAGGBLE = "DRAGGBLE";
const BRA = "BAR";


const draggable = (item, id) => {
    return {
        type: DRAGGBLE,
        id,
        data: item
    }
}

const insertBars = (list) => {
    let i = 0;

    const newBar = () => {
        return {
            type: BRA,
            id: i++
        }
    }

    return [newBar()].concat(
        ...list.map(item => {
            return [draggable(item, i++), newBar()]
        })


    )

}

const useDraggable = (list) => {
    const { dragList } = useState(() => {
        insertBars(list)
    })

    const [dragOver, setDragOver] = useState(null)
    const [dragging, setDragging] = useState(null)

    return {
        dragList,
        createDropperProps: id => {
            return {
                // id,
                key: id,
                dragging,
                dragOver,
                enetHandlers: {
                    onDragOver: e => {
                        e.preventDefault()
                        setDragOver(id)
                    },
                    onDragLeave: e => {
                        e.preventDefault()
                        setDragOver(null)
                    }
                }
            }
        },
        createDraggerProps: id => {
            return {
                id,
                key: id,
                dragging,
                eventHandlers: {
                    onDragStart: () => {
                        setDragging(id)
                    },
                    onDragEnd: () => {
                        setDragging(null)
                    }
                }
            }
        }
    }
}

export default useDraggable;
